package HibernateOrederManagement.app;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import HibernateOrderManagerment.bean.Goods;

public class GoodsDao {
	private Session session;
	
	public GoodsDao(Session session){
		this.session=session;
	}
	
	public List<Goods> list(){
		Query<Goods> query=session.createQuery("from Goods",Goods.class);
		
		return query.getResultList();
	}
	
	public Goods getGoodsById(long id){
		return session.get(Goods.class, id);
	}
	
	public Goods getByType(String type){
		Query<Goods> query =session.createQuery("from Goods where type=:name",Goods.class);
		query.setParameter("name", type);
		return query.getSingleResult();
	}
	public Goods getByName(String name){
		Query<Goods> query =session.createQuery("from Goods where name=:name",Goods.class);
		query.setParameter("name", name);
		return query.getSingleResult();
	}
	public void insert(Goods goods) {
		Transaction tx = session.beginTransaction();
		try {

			session.save(goods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void update(Goods goods){
		Transaction tx = session.beginTransaction();
		try {

			session.update(goods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}
	public <T> void delete(Goods goods){
		Transaction tx = session.beginTransaction();
		try {
			
			session.delete(goods);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}



}
